// 向页面注入JS
function injectCustomJs(jsPath) {
    jsPath = jsPath || 'js/inject.js';
    console.log(jsPath);
    var temp = document.createElement('script');
    temp.setAttribute('type', 'text/javascript');
    // 获得的地址类似：chrome-extension://ihcokhadfjfchaeagdoclpnjdiokfakg/js/inject.js
    temp.src = chrome.extension.getURL(jsPath);
    temp.onload = function () {
        // 放在页面不好看，执行完后移除掉
        this.parentNode.removeChild(this);
    };
    document.body.appendChild(temp);
}

// 接收来自popup的消息
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
    console.log('收到消息：');
    console.log(request, sender, sendResponse);

    switch (request.cmd) {
        case 'start':
            sendResponse({ message: '开始抢小米5pro！' });
            injectCustomJs('js/injects/start.js');
            break;

        case 'stop':
            sendResponse({ message: '停止抢小米！' });
            injectCustomJs('js/injects/stop.js');
            break;

        default:
            sendResponse({ message: '未知的命令！' });
            break;
    }
});
